package org.groupg.project;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public class DebugUtils {
    static Logger log = LoggerFactory.getLogger(DebugUtils.class);
    // 1. 事件追踪器
    public static class EventTracker {
        private final AtomicInteger produced = new AtomicInteger(0);
        private final AtomicInteger transformed = new AtomicInteger(0);
        private final AtomicInteger passedToRx = new AtomicInteger(0);
        private final AtomicInteger consumed = new AtomicInteger(0);

        public void eventProduced() { produced.incrementAndGet(); }
        public void eventTransformed() { transformed.incrementAndGet(); }
        public void eventPassedToRx() { passedToRx.incrementAndGet(); }
        public void eventConsumed() { consumed.incrementAndGet(); }

        public void printStats() {
            log.info("\n===== 事件追踪 =====");
            log.info("生产事件: {}", produced.get());
            log.info("转换事件: {}", transformed.get());
            log.info("传递到RxJava: {}", passedToRx.get());
            log.info("消费事件: {}", consumed.get());
            log.info("Disruptor积压: {}", transformed.get() - passedToRx.get());
            log.info("RxJava积压: {}", passedToRx.get() - consumed.get());
        }
    }

    // 2. 死锁检测器
    public static void deadlockDetector() {
        new Thread(() -> {
            AtomicBoolean running = new AtomicBoolean(true);
            while (running.get()) {
                try {
                    Thread.sleep(5000);
                    log.info("\n===== 线程状态监控 =====");

                    // 获取所有线程
                    Map<Thread, StackTraceElement[]> allThreads = Thread.getAllStackTraces();

                    // 打印阻塞线程
                    allThreads.forEach((thread, stack) -> {
                        if (thread.getState() == Thread.State.BLOCKED ||
                            thread.getState() == Thread.State.WAITING) {
                            log.info("阻塞线程: {} - 状态: {}", thread.getName(), thread.getState());
                            for (StackTraceElement element : stack) {
                                log.info("\t{}", element);
                            }
                        }
                    });
                } catch (Exception e) {
                    running.set(false);
                }
            }
        }, "DeadlockDetector").start();
    }
}